﻿using System.IO;
using System.Windows;
using Microsoft.Win32;

namespace DesktopToyWpf.Services;

public static class StartupManager
{
    // 系统级开机启动注册表路径
    private const string RunKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";

    /// <summary>
    /// 设置或取消程序开机启动
    /// </summary>
    /// <param name="enable">是否启用开机启动</param>
    /// <param name="appName">程序名称（注册表中显示的名称）</param>
    /// <returns>操作是否成功</returns>
    public static bool SetStartup(bool enable)
    {
        try
        {
            // var appPath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
            var appPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DesktopToy.exe");

            // 验证程序路径是否有效
            if (!File.Exists(appPath))
            {
                throw new FileNotFoundException("程序路径不存在", appPath);
            }

            // 打开系统级注册表项（需要管理员权限）
            using var runKey = Registry.CurrentUser.OpenSubKey(RunKeyPath, writable: true);
            if (runKey == null)
            {
                throw new InvalidOperationException("无法打开启动项注册表项，可能没有足够的权限");
            }
    
            if (enable)
            {
                runKey.SetValue(Global.AppName, appPath);
            }
            else
            {
                if (runKey.GetValue(Global.AppName) != null)
                {
                    runKey.DeleteValue(Global.AppName);
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show($"设置开机启动失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 检查程序是否已设置开机启动
    /// </summary>
    /// <param name="appName">程序名称</param>
    /// <returns>是否已设置开机启动</returns>
    public static bool IsStartupEnabled()
    {
        try
        {
            using var runKey = Registry.CurrentUser.OpenSubKey(RunKeyPath);
            return runKey?.GetValue(Global.AppName) != null;
        }
        catch
        {
            return false;
        }
    }
}